// pages/home/home.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    key: [],
    region: ['山西省', '晋中市', '榆次区'],
    containShow: true,
    searchShow: false,
    _year: '',
    _mouth: '',
    _day: '',
    _hour: '',
    _minutes: '',
    _second: '',
    pingjiayu: ['店长推荐', '火热预约', '评价极高', '全新服务'],
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(wx.getStorageSync('dengji') == ''){
      wx.setStorageSync('dengji', 0)
    }
   
    console.log(111)
    // wx.showLoading()
    app.globalData.latitude = wx.setStorageSync('latitude')
    app.globalData.longitude = wx.getStorageSync('longitude')
    // if(wx.getStorageSync('phone') == ''){
    //   wx.switchTab({
    //     url: '/pages/myself/myself',
    //   })
    // }
    if (app.globalData.isOnload != true) {
      app.globalData.phone = wx.getStorageSync('phone')
      app.globalData.BarHeight = wx.getSystemInfoSync().statusBarHeight + 44
      this.setData({
        BarHeight: app.globalData.BarHeight
      })
      this.onProduct();
      this.onChecked();
      this.onService();
      this.onService_items();
      this.onaddress();
      // setInterval(() => {
      // console.log(1)
      // if (wx.getStorageSync('phone') != undefined) {
      //   this.oncheck();

      // }
      // }, 200);
      console.log(this.data.key)
      var that = this


    }

    app.globalData.isOnload = true
  },
  onaddress() {
    let tableName = 'userAddress'
    let Product = new wx.BaaS.TableObject(tableName)
    let query = new wx.BaaS.Query()
    query.compare('userPhone', '=', app.globalData.phone)
    Product.setQuery(query).find().then(res => {
      // success
      console.log(res.data.objects[0].userAllAddress.length)

      for (var i = 0; i < res.data.objects[0].userAllAddress.length / 5; i++) {
        console.log(res.data.objects[0].userAllAddress.length / 5)
        if (res.data.objects[0].userAllAddress[i * 5 + 4] == 1) {
          app.globalData.address = res.data.objects[0].userAllAddress[i * 5 + 3] + ' ' + res.data.objects[0].userAllAddress[i * 5 + 1]
        }
      }
      console.log(app.globalData.address)
    }, err => {
      // err
      console.log('没有找到')
    })
  },

  pingtuan: function (e) {
    setTimeout(function (e) {
      wx.navigateTo({
        url: '/pages/pingtuan/pingtuan',
      })
    }, 200)
  },
  onService_items() {
    let tableName = 'service_items'

    let Query = new wx.BaaS.Query()
    // Query.compare('product_code', '=', that.data.cart[i].product_code)
    let Product = new wx.BaaS.TableObject(tableName)
    Product.setQuery(Query).limit(1000).offset(0).find().then(res => {
      // success
      console.log(res)
      if (wx.getStorageSync('phone') != undefined) {
        this.oncheck();
        // console.log(2)
        // clearInterval()
      }
      var q = res.data.objects
      for(var i = 0 ; i<res.data.objects.length ; i++){
        q[i].actual_price = app.cost(wx.getStorageSync('dengji'),q[i].all_price)
      }
      app.globalData.service_items = q //知晓云获取产品内容
      app.globalData.service_items_sum = q.length
      console.log(app.globalData.service)
      console.log('service_items_sum:' + app.globalData.service_sum);
     
      
    }, err => {
      // err
    })
  },
  onService() {
    let tableName = 'service'

    let Query = new wx.BaaS.Query()
    // Query.compare('product_code', '=', that.data.cart[i].product_code)
    let Product = new wx.BaaS.TableObject(tableName)
    Product.setQuery(Query).limit(1000).offset(0).find().then(res => {
      // success
      console.log(res)
      app.globalData.service = res.data.objects //知晓云获取产品内容
      app.globalData.service_sum = res.data.objects.length
      console.log('service:' + app.globalData.service)
      console.log('service_sum:' + app.globalData.service_sum)
    }, err => {
      // err
    })
  },
  oncheck() {
    console.log(3333333)
    var item = [
      ['G', 'H', 'I', 'J', 'K', 'L'],
      ['M', 'N', 'O', 'P', 'Q', 'R'],
      ['S', 'T', 'U', 'V', 'W', 'X'],
      ['Y', 'Z', 'k', '?', '/', '|'],
      ['7', '0', '@', '!', '~', '@'],
      ['1', '2', '3', '4', '5', '6'],
      ['$', '-', '=', '&', 'T', '#'],
      ['&', '9', '8', '%', '+', '?'],
      ['A', 'B', 'C', 'D', 'E', 'F'],
      ['a', 'b', 'c', 'd', 'e', 'f']
    ]
    var that = this
    if (wx.getStorageSync('product_kan_sum') != '') {
      if (wx.getStorageSync('product_Sname') == '') {
        var h = app.globalData.phone.split('')
        var id = ''
        for (var j = 0; j < h.length; j++) {
          var a = Math.floor(Math.random() * 5)
          id = id.concat(item[h[j]][a])

        }
        console.log(id)
        wx.setStorageSync('product_Sname', id)
      }
      var time = new Date();
      var year = time.getFullYear()
      var mouth = time.getMonth() + 1
      var day = time.getDate()
      var date = year + '-' + mouth + '-' + day

      if (wx.getStorageSync('k') == 1) {
        var prodcut = wx.getStorageSync('product_kan_sum')
        console.log(prodcut)
        var item = []
        var kkkk = []
        for (var j = 0; j < prodcut.length; j++) {
          var sum = 0
          var _sum = 0
          for (var i = 0; i < prodcut[j].time.length; i++) {
            var end = timeFn(prodcut[j].time[i])
            console.log(end)
            if (end <= 7) {
              sum = sum + 1
            }
            if (end <= 30) {
              _sum = _sum + 1
            }
          }
          var items = prodcut[j].product_code + ',' + wx.getStorageSync('product_Sname') + ',' + sum.toString() + ',' + _sum.toString() + ',' + date
          item.push(items)
          var d = []
          var m = 0
          console.log(app.globalData.product_sum)
          for (var o = 0; o < app.globalData.product_sum; o++) {
            console.log(111)
            if (prodcut[j].id == app.globalData.product[o].id) {
              d = app.globalData.product[o].shuju
              if (d != null) {
                for (var k = 0; k < d.length; k++) {
                  console.log(d[k].split(',')[1])
                  if (d[k].split(',')[1] == wx.getStorageSync('product_Sname')) {
                    d[k] = items,
                      m = 1
                  }
                }
              }
              if (m == 0) {
                if (d == null) {
                  d = []
                }
                d.push(items)
              }
              console.log(d, m)
            }
          }

          let tableName = 'product'
          let recordID = prodcut[j].id // 数据行 id

          let Product = new wx.BaaS.TableObject(tableName)
          let product = Product.getWithoutData(recordID)

          product.set('shuju', d)
          product.update().then(res => {
            // success
            console.log(res)
            wx.setStorageSync('k', 0)
          }, err => {
            // err
          })
        }
        console.log(item)

      }

      if (wx.getStorageSync('k_') == 1) {
        var prodcut = wx.getStorageSync('service_kan_sum')
        console.log(prodcut)
        var itemss = []

        for (var j = 0; j < prodcut.length; j++) {
          var sum_ = 0
          var sum__ = 0
          for (var i = 0; i < prodcut[j].time.length; i++) {

            var end = timeFn(prodcut[j].time[i])
            console.log(end)
            if (end <= 7) {
              sum_ = sum_ + 1
            }
            if (end <= 30) {
              sum__ = sum__ + 1
            }
            var itemsss = prodcut[j].service_code + ',' + wx.getStorageSync('product_Sname') + ',' + sum_.toString() + ',' + sum__.toString() + ',' + date
            itemss.push(itemsss)
            var dd = []
            var mm = 0
            for (var o = 0; o < app.globalData.service_items_sum; o++) {
              console.log(111)
              if (prodcut[j].id == app.globalData.service_items[o].id) {
                console.log(222)
                dd = app.globalData.service_items[o].shuju
                if (dd != null) {
                  for (var k = 0; k < dd.length; k++) {
                    if (dd.split(',')[1] == wx.getStorageSync('service_kan_sum')) {
                      dd[k] = itemsss,
                        mm = 1
                    }
                  }
                }

              }
            }
            console.log(mm)
            if (mm == 0) {
              if (dd == null) {
                dd = []
              }
              dd.push(itemsss)
            }
            console.log(dd)
            let tableName1 = 'service_items'
            let recordID1 = prodcut[j].id // 数据行 id

            let Product2 = new wx.BaaS.TableObject(tableName1)
            let product2 = Product2.getWithoutData(recordID1)
            console.log(dd)
            product2.set('shuju', dd)
            product2.update().then(res => {
              // success
              console.log(res)
              wx.setStorageSync('k_', 0)
            }, err => {
              // err
            })
          }
        }

        console.log(itemsss)
      }


      function timeFn(d1) { //d1作为一个变量传进来
        //如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
        var dateBegin = new Date(d1.replace(/-/g, "/")); //将-转化为/，使用new Date
        var dateEnd = new Date(); //获取当前时间
        var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
        var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数

        if (dayDiff >= 0) {
          return dayDiff
        }

      }

    }
  },
  //获取所有产品信息
  onProduct() {
    let tableName = 'product'

    let Query = new wx.BaaS.Query()
    // Query.compare('product_code', '=', that.data.cart[i].product_code)
    let Product = new wx.BaaS.TableObject(tableName)
    Product.setQuery(Query).limit(1000).offset(0).find().then(res => {
      // success
      var q = res.data.objects
      for(var i = 0 ; i<res.data.objects.length ; i++){
        q[i].cost = app.cost(wx.getStorageSync('dengji'),q[i].pre_cost)
      }
      app.globalData.product = q //知晓云获取产品内容
      app.globalData.product_sum = q.length
      console.log(app.globalData.product)
      console.log('product_sum:' + app.globalData.product_sum)

      var item = []
      var _year
      var _mouth
      var _day
      var _hour
      var _minutes
      for (var i = 0; i < res.data.objects.length; i++) {
        if(res.data.objects[i].product_end_time!=0){
          
            item.push(res.data.objects[i])
          
          
            var time = res.data.objects[i].product_end_time.split(' ')
            console.log(res.data.objects[i].product_end_time.split(' '))
            
            var ri = time[0].split('-')
            var shi = time[1].split(':')
            _year = ri[0]
            _mouth = ri[1]
            _day = ri[2]
            _hour = shi[0]
            _minutes = shi[1]
            if (shi[2] != undefined) {
              _second = shi[2]
            }
            this.setData({
              _day: _day,
              _hour: _hour,
              _minutes: _minutes,
              _year: _year,
              _mouth: _mouth,
              _day: _day,
      
            })
          
        }
       
      }

     
      var time = new Date()
      var that = this
      var app_ = setInterval(function (e) {

        var end_time = timeFn(that.data._year + '/' + that.data._mouth + '/' + that.data._day + ' ' + that.data._hour + ':' + that.data._minutes + ':' + that.data._second)
        // console.log(end_time)
        if (end_time != 0) {
          that.setData({
            end_time: end_time,
            xianshi: item
          })
        } else {
          that.setData({
            end_time: 0
          })
          clear()
        }

        app.globalData.xianshi = item
      }, 1000)

      function clear(e) {
        clearInterval(app_)
      }

      function timeFn(d1) { //d1作为一个变量传进来
        //如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
        var dateBegin = new Date(d1.replace(/-/g, "/")); //将-转化为/，使用new Date
        var dateEnd = new Date(); //获取当前时间
        var dateDiff = dateEnd.getTime()-dateBegin.getTime()  ; //时间差的毫秒数
        var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
        var leave1 = dateDiff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000)) //计算出小时数
        //计算相差分钟数
        var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000)) //计算相差分钟数
        //计算相差秒数
        var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000)
        // console.log(" 相差 " + dayDiff + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒")
        // console.log(dateDiff + "时间差的毫秒数", dayDiff + "计算出相差天数", leave1 + "计算天数后剩余的毫秒数", hours + "计算出小时数", minutes + "计算相差分钟数", seconds + "计算相差秒数");
        if (dayDiff <= 0) {
          // console.log(111)
          return  (0-dayDiff).toString() + '天' + (0 - hours) + ':' + (0-minutes) + ':' + (0 - seconds)
        } else {
          // console.log(1111)
          return 0
        }

      }

    }, err => {
      // err
    })
  },
  phone: function (e) {
    wx.makePhoneCall({
      phoneNumber: '400-777-1820',
    })
  },
  onChecked() {
    //热门商品
    var that = this
    let tableName = 'product'

    let Query = new wx.BaaS.Query()
    Query.compare('hot', '=', parseInt(1))
    let Product = new wx.BaaS.TableObject(tableName)
    Product.setQuery(Query).limit(1000).offset(0).find().then(res => {
      // success
      console.log(res)
      that.setData({
        key: res.data.objects, //热门商品
      })
      app.globalData.key = this.data.key
      console.log(that.data.key)
    }, err => {
      // err
    })
  },

  onBindFocus() {
    wx.navigateTo({
      url: '../search/search'

    })
  },

  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },

  shouCang() {
    wx.navigateTo({
      url: '../shoucang/shoucang',
    })
  },

  shangpinDetail(e) {
    console.log(e.currentTarget.dataset)
    var postId = e.currentTarget.dataset.postid
    setTimeout(function (e) {
      wx.navigateTo({
        url: '../post-detail/post-detail?id=' + postId
      })
    }, 200)

  },

  gengDuo(e) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    setTimeout(function () {
      wx.stopPullDownRefresh();
      wx.showToast({
        title: '刷新成功',
        icon: 'none'
      })
    }, 1000);
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  yuyue: function (e) {
    wx.navigateTo({
      url: '/pages/detailAddress/detailAddress',
    })
  }
})